/*
 * 系统主体业务实现
 */
var App = function() {
	/********************************************************
	 * 私有变量
	 ********************************************************/
	//数据库连接
	var _conn = null;
	//数据库文件
	var _dbfile = null;
	//SQLStatement
	var _stmt = null;
	//sql status
	var _sqlstatus = "";
	//程序配置信息表是否有数据
	var _configcount = 0;
	//配置信息
	var _configinfo = null;
	//部门列表
	var _deptList = null;
	//二级部门列表
	var _subDeptList = null;
	//用户列表
	var _userList = null;
	//缓存用户信息
	var _cacheInfo = null;
	//寻呼接收人列表
	var _sendtousers = null;
	//记录是否已添加关注
	var _carenum = 0;
	//关注人员列表
	var _careuserlist = null;
	//递归部门串时的临时变量
	var _tempdeptid = 0;
	//临时交换数据
	var _tempdata = "";

	/************************************************
	 * 私有函数
	 ***********************************************/
	//sqlite数据库初始化
	function initDB() {
		//读取数据库文件
		_dbfile = air.File.applicationDirectory.resolvePath('app:/assets/db/data.db');
		//创建连接
		_conn = new air.SQLConnection();
		//添加监听
		_conn.addEventListener(air.SQLEvent.OPEN, dbError);
		//打开连接
		_conn.open(_dbfile, air.SQLMode.CREATE);
	}

	function dbError() {
		_stmt = new air.SQLStatement();
		_stmt.addEventListener(air.SQLErrorEvent.ERROR, function(event) {
			alert('There has been a problem executing a statement:\n' + event.error.message);
		});
		_stmt.sqlConnection = _conn;
		_stmt.text = "";
		_stmt.addEventListener(air.SQLEvent.RESULT, doStmtResult);
	}

	function disposeDB() {
		if(_stmt) {
			_stmt.removeEventListener(air.SQLEvent.RESULT, doStmtResult);
			_stmt.sqlConnection = null;
			_stmt = null;
		}
		if(_conn) {
			_conn.removeEventListener(air.SQLEvent.OPEN, dbError);
			_conn = null;
		}
	}

	//数据库查询执行
	function doStmtResult() {
		switch(_sqlstatus) {
			//检查程序配置信息是否存在
			case "checkconfig":
				var result = _stmt.getResult();
				if(result.data == null) {
					_configcount = 0;
				} else {
					_configcount = Math.round(result.data[0]["num"]);
				}
				break;
			//获取程序配置信息
			case "getconfig":
				var result = _stmt.getResult();
				if(result.data == null) {
					_configinfo = null;
				} else {
					_configinfo = {};
					for(var i = 0; i < result.data.length; i++) {
						_configinfo[result.data[i]["Key"]] = result.data[i]["Value"];
					}
				}
				break;
			//获取第一级部门
			case "getfirstdept":
				var result = _stmt.getResult();
				if(result.data == null) {
					_deptList = null;
				} else {
					_deptList = new Array();
					for(var i = 0; i < result.data.length; i++) {
						_deptList[i] = {};
						_deptList[i].deptId = result.data[i]["DeptID"];
						_deptList[i].deptName = result.data[i]["DeptName"];
						_deptList[i].fatherId = result.data[i]["DeptFID"];
						_deptList[i].level = result.data[i]["Level"];
					}
				}
				break;
			//获取次级部门
			case "getsubdept":
				var result = _stmt.getResult();
				if(result.data == null) {
					_subDeptList = null;
				} else {
					_subDeptList = new Array();
					for(var i = 0; i < result.data.length; i++) {
						_subDeptList[i] = {};
						_subDeptList[i].deptId = result.data[i]["DeptID"];
						_subDeptList[i].deptName = result.data[i]["DeptName"];
						_subDeptList[i].fatherId = result.data[i]["DeptFID"];
						_subDeptList[i].level = result.data[i]["Level"];
					}
				}
				break;
			//获取用户列表
			case "getuser":
				var result = _stmt.getResult();
				if(result.data == null) {
					_userList = null;
				} else {
					_userList = new Array();
					for(var i = 0; i < result.data.length; i++) {
						_userList[i] = {};
						_userList[i].posiId = result.data[i]["PosiID"];
						_userList[i].userName = result.data[i]["UserName"];
						_userList[i].userId = result.data[i]["UserID"];
						_userList[i].deptId = result.data[i]["DeptID"];
						_userList[i].color = result.data[i]["Color"];
					}
				}
				break;
			//提取缓存信息
			case "getcacheinfo":
				var result = _stmt.getResult();
				if(result.data == null) {
					_cacheInfo = null;
				} else {
					_cacheInfo = {}
					_cacheInfo.org = result.data[0]["Org"];
				}
				break;
			//获取寻呼接收人
			case "getsendtousers":
				var result = _stmt.getResult();
				if(result.data == null) {
					_sendtousers = null;
				} else {
					_sendtousers = new Array();
					for(var i = 0; i < result.data.length; i++) {
						_sendtousers[i] = {};
						_sendtousers[i].userId = result.data[i]["UserID"];
						_sendtousers[i].userName = result.data[i]["UserName"];
					}
				}
				break;
			//判断是否是关注人员
			case "checkcare":
				var result = _stmt.getResult();
				if(result.data == null) {
					_carenum = 0;
				} else {
					_carenum = Math.round(result.data[0]["Num"]);
				}
				break;
			//获取所有的关注人员列表
			case"getcareuserlist":
				var result = _stmt.getResult();
				if(result.data == null) {
					_careuserlist = null;
				} else {
					_careuserlist = new Array();
					for(var i = 0; i < result.data.length; i++) {
						_careuserlist[i] = {};
						_careuserlist[i].userID = result.data[i]["UID"];
						_careuserlist[i].userName = result.data[i]["UserName"];
						_careuserlist[i].deptName = result.data[i]["DeptName"];
						_careuserlist[i].posiName = result.data[i]["PosiName"];
						_careuserlist[i].teleNum = result.data[i]["TeleNum"];
						_careuserlist[i].userTel = result.data[i]["UserTel"];
						_careuserlist[i].tUID = result.data[i]["TUID"];
					}
				}
				break;
			//用户所在部门编号
			case "getsearchdata":
				var result = _stmt.getResult();
				if(result.data == null) {
					_tempdeptid = 0;
				} else {
					_tempdeptid = result.data[0]["DeptID"];
				}
				break;
			//部门父级部门编号
			case "getfsearchdata":
				var result = _stmt.getResult();
				if(result.data == null) {
					_tempdeptid = 0;
				} else {
					_tempdeptid = result.data[0]["DeptFID"];
				}
				break;
			//提取临时交换数据
			case "gettempdata":
				var result = _stmt.getResult();
				if(result.data == null) {
					_tempdata = "";
				} else {
					_tempdata = result.data[0]["Data"];
				}
				break;
			default:
				break;
		}
	}

	//获取部门列表，递归(内部函数)
	function GetDeptNodes(deptNode) {
		var nodeStr = "<div dept='" + deptNode.deptName + "' flag='1' id='dept_" + deptNode.deptId + "' class=\"dnode\">" + deptNode.deptName + "</div><div class=\"cnode\">";
		for(var i = 0; i < deptNode.childUsers.length; i++) {
			nodeStr += "<div  flag='1' id='user_" + deptNode.childUsers[i].userId + "' class=\"unode\">" + deptNode.childUsers[i].userName + "</div>";
		}
		if(deptNode.childNodes.length != 0) {
			for(var i = 0; i < deptNode.childNodes.length; i++) {
				nodeStr += GetDeptNodes(deptNode.childNodes[i]);
			}
		}
		nodeStr += "</div>";
		return nodeStr;
	}

	//缓存部门列表到本地数据库减少网络请求次数
	function CacheDeptNodes(deptNode) {
		_stmt.clearParameters();
		_stmt.text = "insert into dept(DeptID,DeptFID,DeptName,Level) values(@DeptID,@DeptFID,@DeptName,@Level)";
		_stmt.parameters["@DeptID"] = deptNode.deptId;
		_stmt.parameters["@DeptName"] = deptNode.deptName;
		_stmt.parameters["@DeptFID"] = deptNode.fatherId;
		_stmt.parameters["@Level"] = deptNode.level;
		_stmt.execute();

		for(var i = 0; i < deptNode.childUsers.length; i++) {
			_stmt.clearParameters();
			_stmt.text = "insert into user(UserID,UserName,DeptID,PosiID,Color) values(@UserID,@UserName,@DeptID,@PosiID,@Color)";
			_stmt.parameters["@UserID"] = deptNode.childUsers[i].userId;
			_stmt.parameters["@UserName"] = deptNode.childUsers[i].userName;
			_stmt.parameters["@DeptID"] = deptNode.deptId;
			_stmt.parameters["@PosiID"] = deptNode.childUsers[i].posiId;
			_stmt.parameters["@Color"] = deptNode.childUsers[i].color;
			_stmt.execute();
		}
		if(deptNode.childNodes.length != 0) {
			for(var i = 0; i < deptNode.childNodes.length; i++) {
				CacheDeptNodes(deptNode.childNodes[i]);
			}
		}
	}

	//检测某用户是否在关注列表
	function CheckCare(uid) {
		var config = App.getConfig();
		//打开数据库连接
		initDB();
		_stmt.clearParameters();
		_stmt.text = "select count(*) Num from UserCare where UID = @UID and TUID = @TUID";
		_stmt.parameters["@UID"] = uid;
		_stmt.parameters["@TUID"] = config.LoginCode;
		_sqlstatus = "checkcare";
		_stmt.execute();
		//销毁数据库连接
		disposeDB();
		if(_carenum == 0)
			return false;
		else
			return true;
	}

	//递归获取某个用户所在部门的串1,1001,1011
	function GetFDept(deptid, deptlist) {
		//打开数据库连接
		initDB();
		_stmt.clearParameters();
		_stmt.text = "select * from dept where deptid = @deptid";
		_stmt.parameters["@deptid"] = deptid;
		_sqlstatus = "getfsearchdata";
		_stmt.execute();
		//销毁数据库连接
		disposeDB();
		deptlist.push(_tempdeptid);
		if(_tempdeptid === 0) {
			return;
		} else {
			GetFDept(_tempdeptid, deptlist);
		}
	}

	//初始化数据库，一直保持数据库连接
	//initDB();

	/***************************************************
	 * public function
	 *************************************************/
	return {
		//检测是否需要更新，目前暂定24小时
		CheckUpdate : function() {
			//检查是否需要更新
			var isupdate = false;
			var cacheInfo = App.getCacheInfo();
			var slice = 0;
			if(cacheInfo == null)
				slice = 0
			else
				slice = Math.round((new Date()).valueOf()) - Math.round(cacheInfo.org);
			if(slice == 0 || slice > Const.org._timeout) {
				isupdate = true;
			}
			return isupdate;
		},
		//更新缓存时间
		UpdateCache : function(obj, value) {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "update cache set " + obj + " = @" + obj;
			_stmt.parameters["@" + obj] = value;
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
		},
		//获取配置信息
		getConfig : function() {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "select * from config";
			_sqlstatus = "getconfig";
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
			return _configinfo;
		},
		//设置配置信息
		setConfig : function(Config) {
			//打开数据库连接
			initDB();
			var keys = new Array();
			var values = new Array();
			var kstr = "";
			var pstr = "";
			var ustr = "";
			for(name in Config) {
				if( typeof Config[name] !== 'function') {
					if(Config[name] == "") {
						if(Config[name] === 0) {
							Config[name] = "0";
							keys.push(name);
							values.push(Config[name].toString());
						}
					} else {
						if(Config[name] === 0) {
							Config[name] = "0";
						}
						keys.push(name);
						values.push(Config[name].toString());
					}
				}
			}
			_conn.begin();
			for(var i = 0; i < keys.length; i++) {
				_stmt.clearParameters();
				_stmt.text = "update config set Value = @" + keys[i] + " where Key='" + keys[i] + "'";
				_stmt.parameters["@" + keys[i]] = values[i];
				_sqlstatus = "setconfig";
				_stmt.execute();
			}
			_conn.commit();
			//销毁数据库连接
			disposeDB();
		},
		//登录
		login : function(loginCode, pwd, rembPwd, autoLogin, callback, error) {
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/Authorize";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = loginCode + "$" + SHA1.hex_sha1_u(pwd);
			//返回数据类型
			variables.dataType = "json";
			var loginInfo = Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					if(config.LoginCode !== loginCode) {
						config.CallNum = "0";
					}
					config.LoginCode = loginCode;
					config.Password = pwd;
					config.RembPwd = rembPwd;
					config.AutoLogin = autoLogin;
					App.setConfig(config);
					callback();
				}
			}, function(data) {
				error(data);
			})
		},
		//获取登录账号信息
		getUserInfo : function(loginCode, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetUserInfo";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback(data);
				}
			}, function(data) {
				error(data);
			});
		},
		//缓存组织架构信息
		cacheUserList : function(data) {
			//打开数据库连接
			initDB();
			//清空所有部门
			_stmt.clearParameters();
			_stmt.text = "delete from dept";
			_stmt.execute();
			//清空所有用户
			_stmt.clearParameters();
			_stmt.text = "delete from user";
			_stmt.execute();
			//缓存数据
			_conn.begin();
			for(var i = 0; i < data.deptList.length; i++) {
				_stmt.clearParameters();
				_stmt.text = "insert into dept(DeptID,DeptFID,DeptName,Level) values(@DeptID,@DeptFID,@DeptName,@Level)";
				_stmt.parameters["@DeptID"] = data.deptList[i].deptId;
				_stmt.parameters["@DeptName"] = data.deptList[i].deptName;
				_stmt.parameters["@DeptFID"] = data.deptList[i].fatherId;
				_stmt.parameters["@Level"] = data.deptList[i].level;
				_stmt.execute();

				for(var k = 0; k < data.deptList[i].childUsers.length; k++) {
					_stmt.clearParameters();
					_stmt.text = "insert into user(UserID,UserName,DeptID,PosiID,Color) values(@UserID,@UserName,@DeptID,@PosiID,@Color)";
					_stmt.parameters["@UserID"] = data.deptList[i].childUsers[k].userId;
					_stmt.parameters["@UserName"] = data.deptList[i].childUsers[k].userName;
					_stmt.parameters["@DeptID"] = data.deptList[i].deptId;
					_stmt.parameters["@PosiID"] = data.deptList[i].childUsers[k].posiId;
					_stmt.parameters["@Color"] = data.deptList[i].childUsers[k].color;
					_stmt.execute();
				}
				for(var j = 0; j < data.deptList[i].childNodes.length; j++) {
					CacheDeptNodes(data.deptList[i].childNodes[j]);
				}
			}
			_conn.commit();
			//销毁数据库连接
			disposeDB();
		},
		//通过缓存加载组织架构
		getUserListFromCache : function(callback) {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "select * from dept where deptfid = 0";
			_sqlstatus = "getfirstdept";
			_stmt.execute();

			if(_deptList == null) {
				//销毁数据库连接
				disposeDB();
				callback("");
			} else {
				var org = "<div class=\"org\">";
				for(var i = 0; i < _deptList.length; i++) {
					org += "<div dept='" + _deptList[i].deptName + "'  flag='1' id='dept_" + _deptList[i].deptId + "' class=\"hnode\">" + _deptList[i].deptName + "</div>";
					org += "<div  class=\"cnode\">";
					//
					if(_deptList[i].deptName.indexOf('******') < 0) {
						_stmt.clearParameters();
						_stmt.text = "select * from user where deptid= @deptid";
						_stmt.parameters["@deptid"] = _deptList[i].deptId;
						_sqlstatus = "getuser";
						_stmt.execute();
						if(_userList != null) {
							for(var k = 0; k < _userList.length; k++) {
								if(_userList[k].color == "red") {
									org += "<div status='online' style='background-image: url(assets/images/org/online.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
								} else if(_userList[k].color == "#ff00bb") {
									org += "<div status='online' style='color:blue;background-image: url(assets/images/org/online.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
								} else if(_userList[k].color == "blue") {
									org += "<div status='offline' style='color:blue;background-image: url(assets/images/org/offline.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
								} else {
									org += "<div status='offline' style='background-image: url(assets/images/org/offline.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
								}
							}
						}
					}
					//
					_stmt.clearParameters();
					_stmt.text = "select * from dept where deptfid = @deptid";
					_stmt.parameters["@deptid"] = _deptList[i].deptId;
					_sqlstatus = "getsubdept";
					_stmt.execute();
					if(_subDeptList != null) {
						for(var j = 0; j < _subDeptList.length; j++) {
							org += "<div dept='" + _subDeptList[j].deptName + "'  flag='1' id='dept_" + _subDeptList[j].deptId + "' class=\"dnode\">" + _subDeptList[j].deptName + "</div>";
						}
					}
					org += "</div>";
				}
				org += "</div>";
				//销毁数据库连接
				disposeDB();
				callback(org);
			}
		},
		//异步加载子部门和用户
		getChildUserList : function(deptId) {
			//打开数据库连接
			initDB();
			var org = "<div  class=\"cnode\">";
			//
			_stmt.clearParameters();
			_stmt.text = "select * from user where deptid= @deptid";
			_stmt.parameters["@deptid"] = deptId;
			_sqlstatus = "getuser";
			_stmt.execute();
			if(_userList != null) {
				for(var k = 0; k < _userList.length; k++) {
					if(_userList[k].color == "red") {
						org += "<div status='online' style='background-image: url(assets/images/org/online.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
					} else if(_userList[k].color == "#ff00bb") {
						org += "<div status='online' style='color:blue;background-image: url(assets/images/org/online.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
					} else if(_userList[k].color == "blue") {
						org += "<div status='offline' style='color:blue;background-image: url(assets/images/org/offline.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
					} else {
						org += "<div status='offline' style='background-image: url(assets/images/org/offline.png);' flag='1' id='user_" + _userList[k].userId + "' class=\"unode\">" + _userList[k].userName + "</div>";
					}
				}
			}
			//
			_stmt.clearParameters();
			_stmt.text = "select * from dept where deptfid = @deptid";
			_stmt.parameters["@deptid"] = deptId;
			_sqlstatus = "getsubdept";
			_stmt.execute();
			if(_subDeptList != null) {
				for(var j = 0; j < _subDeptList.length; j++) {
					org += "<div dept='" + _subDeptList[j].deptName + "'  flag='1' id='dept_" + _subDeptList[j].deptId + "' class=\"dnode\">" + _subDeptList[j].deptName + "</div>";
				}
			}
			org += "</div>";
			//销毁数据库连接
			disposeDB();
			return org;
		},
		//首次加载组织架构，网络请求数据
		getUserList : function(callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetUserList";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			//请求数据格式
			variables.dataStyle = "0";
			//返回数据类型
			variables.dataType = "json";
			Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {

					/*异步加载数据*/
					var org = "<div class=\"org\">";
					for(var i = 0; i < data.deptList.length; i++) {
						org += "<div dept='" + data.deptList[i].deptName + "'  flag='1' id='dept_" + data.deptList[i].deptId + "' class=\"hnode\">" + data.deptList[i].deptName + "</div>";
						org += "<div  class=\"cnode\">";
						if(data.deptList[i].deptName.indexOf('******') < 0) {
							for(var k = 0; k < data.deptList[i].childUsers.length; k++) {
								var markColor = data.deptList[i].childUsers[k].color.toLowerCase();
								if(markColor == "red") {
									org += "<div status='online' style='background-image: url(assets/images/org/online.png);' flag='1' id='user_" + data.deptList[i].childUsers[k].userId + "' class=\"unode\">" + data.deptList[i].childUsers[k].userName + "</div>";
								} else if(markColor == "#ff00bb") {
									org += "<div status='online' style='color:blue;background-image: url(assets/images/org/online.png);' flag='1' id='user_" + data.deptList[i].childUsers[k].userId + "' class=\"unode\">" + data.deptList[i].childUsers[k].userName + "</div>";
								} else if(markColor == "blue") {
									org += "<div status='offline' style='color:blue;background-image: url(assets/images/org/offline.png);' flag='1' id='user_" + data.deptList[i].childUsers[k].userId + "' class=\"unode\">" + data.deptList[i].childUsers[k].userName + "</div>";
								} else {
									org += "<div status='offline' style='background-image: url(assets/images/org/offline.png);' flag='1' id='user_" + data.deptList[i].childUsers[k].userId + "' class=\"unode\">" + data.deptList[i].childUsers[k].userName + "</div>";
								}
							}
						}
						for(var j = 0; j < data.deptList[i].childNodes.length; j++) {
							org += "<div dept='" + data.deptList[i].childNodes[j].deptName + "'  flag='1' id='dept_" + data.deptList[i].childNodes[j].deptId + "' class=\"dnode\">" + data.deptList[i].childNodes[j].deptName + "</div>";
						}
						org += "</div>";
					}
					org += "</div>";

					//缓存数据
					App.cacheUserList(data);
					App.UpdateCache("org", (new Date()).valueOf());
					//回调
					callback(org);
				}
			}, function(err) {
				error(err);
			});
		},
		//获取缓存时间
		getCacheInfo : function(obj) {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "select * from  cache";
			_sqlstatus = "getcacheinfo";
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
			return _cacheInfo;
		},
		//寻呼发送时的目的用户构造
		getSendToUsers : function(id, callback, error) {
			var flag = id.split("_")[0];
			var tid = id.split("_")[1];
			if(flag == "user") {
				//默认用户已经登录成功
				var config = App.getConfig();
				//web service 登录认证地址
				var url = config.WsURL + "/GetOUserInfo";
				var variables = new air.URLVariables();
				//用户名和密码用$连接
				variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
				//指定用户ID
				variables.userId = tid;
				//返回数据类型
				variables.dataType = "json";
				Net.getJSON(url, variables, function(data) {
					if(data.error == "1") {
						error(data.errorMessage);
					} else {
						//先存图
						if(data.photoCode == null || data.photoCode == "") {

						} else {
							var file = new air.File(air.File.applicationDirectory.resolvePath("app:/assets/images/photos/" + tid + ".jpg").nativePath);
							var byteData = new air.ByteArray();
							Base64.decode(data.photoCode, byteData);
							var stream = new air.FileStream();
							stream.open(file, air.FileMode.WRITE);
							stream.writeBytes(byteData, 0, byteData.length);
							stream.close();
						}
						callback(data);
					}
				}, function(err) {
					error(err);
				});
			} else if(flag == "dept") {
				//待改进为递归
				//打开数据库连接
				initDB();
				_stmt.clearParameters();
				_stmt.text = "select * from user where deptid= @deptid";
				_stmt.parameters["@deptid"] = tid;
				_sqlstatus = "getsendtousers";
				_stmt.execute();
				//销毁数据库连接
				disposeDB();
				var usersinfo = "";
				if(_sendtousers != null) {
					for(var k = 0; k < _sendtousers.length; k++) {
						usersinfo += "<div id='user_" + _sendtousers[k].userId + "' class=\"usercard_s\"><span>" + _sendtousers[k].userName + "</span><span class=\"close\">&nbsp;&nbsp;&nbsp;</span></div>";
					}
				}
				callback(usersinfo);
				//
			} else {
				callback("");
			}
		},
		//寻呼发送
		sendMsg : function(msg, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/SendCall";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			//请求数据格式
			variables.dataStyle = "0";
			//寻呼内容
			variables.strSendContent = msg.strSendContent;
			//目标人
			variables.strSendToUsers = msg.strSendToUsers;
			//是否发短信
			variables.strSmsSign = msg.strSmsSign;
			//手机号
			variables.strMobileNum = msg.strMobileNum;

			//返回数据类型
			variables.dataType = "json";
			Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback();
				}
			}, function(err) {
				error(err);
			});
		},
		//坚持某用户是否在关注列表
		CheckCare : function(uid) {
			var config = App.getConfig();
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "select count(*) Num from UserCare where UID = @UID and TUID = @TUID";
			_stmt.parameters["@UID"] = uid;
			_stmt.parameters["@TUID"] = config.LoginCode;
			_sqlstatus = "checkcare";
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
			if(_carenum == 0)
				return false;
			else
				return true;
		},
		//关注人员
		CareUser : function(userinfo) {
			var config = App.getConfig();

			if(CheckCare(userinfo.userID)) {
				//delete from UserCare where UID = @UID
				//打开数据库连接
				initDB();
				_stmt.clearParameters();
				_stmt.text = "delete from UserCare where UID = @UID and TUID=@TUID";
				_stmt.parameters["@UID"] = userinfo.userID;
				_stmt.parameters["@TUID"] = config.LoginCode;
				_stmt.execute();
			} else {
				//打开数据库连接
				initDB();
				_stmt.clearParameters();
				_stmt.text = "insert into UserCare(TUID,UID,UserName,DeptName,PosiName,TeleNum,UserTel) values(@TUID,@UID,@UserName,@DeptName,@PosiName,@TeleNum,@UserTel)";
				_stmt.parameters["@UID"] = userinfo.userID;
				_stmt.parameters["@UserName"] = userinfo.userName;
				_stmt.parameters["@DeptName"] = userinfo.deptName;
				_stmt.parameters["@PosiName"] = userinfo.posiName;
				_stmt.parameters["@TeleNum"] = userinfo.teleNum;
				_stmt.parameters["@UserTel"] = userinfo.userTel;
				_stmt.parameters["@TUID"] = config.LoginCode;
				_stmt.execute();
			}
			//销毁数据库连接
			disposeDB();
		},
		//加载关注人员
		getCareUserList : function(callback) {
			var config = App.getConfig();
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "select * from UserCare where TUID=@TUID";
			_stmt.parameters["@TUID"] = config.LoginCode;
			_sqlstatus = "getcareuserlist"
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
			var userinfo = "";
			if(_careuserlist == null) {
				callback(userinfo, _careuserlist);
				return;
			}
			for(var i = 0; i < _careuserlist.length; i++) {
				userinfo += "<div flag ='0' id='user_" + _careuserlist[i].userID + "' class=\"usercard_l\"><table cellpadding=\"0\" cellspacing=\"0\">";
				var file = new air.File(air.File.applicationDirectory.resolvePath("app:/assets/images/photos/" + _careuserlist[i].userID + ".jpg").nativePath);
				if(file.exists) {
					userinfo += "<tr><td><img class=\"photoimg\" src=\"assets/images/photos/" + _careuserlist[i].userID + ".jpg\" /></td>";
				} else {
					userinfo += "<tr><td><img class=\"photoimg\" src=\"assets/images/head.gif\" /></td>";
				}
				userinfo += "<td style=\"text-align: left; padding-left: 6px;\">";
				userinfo += "<ul><li>" + _careuserlist[i].userName + "</li>";
				userinfo += "<li>" + _careuserlist[i].deptName + "</li>";
				userinfo += "<li>" + _careuserlist[i].posiName + "</li>";
				userinfo += "<li>" + _careuserlist[i].teleNum + "</li>";
				userinfo += "<li>" + _careuserlist[i].userTel + "</li>";
				userinfo += "</ul></td></tr></table>";
				userinfo += "<div flag = '" + i.toString() + "' class='user_add'></div>";
				//userinfo += "<div class='user_refresh'></div>";
				userinfo += "</div>";
			}
			callback(userinfo, _careuserlist);
		},
		//清空关注人员
		clearCareUsers : function() {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "delete from UserCare";
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
		},
		//请求未阅寻呼数量
		getUnreadMessageNum : function(callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetUnreadMessageNum";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback(data.data);
				}
			}, function(err) {
				error(err);
			});
		},
		//提取最新未阅寻呼
		getLastCallNoSee : function(callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetUnreadMessageList";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			variables.cursor = 1;
			variables.count = 1;
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				var bakInfo = "";
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback(data);
				}
			}, function(err) {
				error(err);
			});
		},
		//未阅寻呼
		getCallNoSee : function(cursor, count, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetUnreadMessageList";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			variables.cursor = cursor.toString();
			variables.count = count.toString();
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				var bakInfo = "";
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					for(var i = 0; i < data.messages.length; i++) {
						bakInfo += "<div id='msg_" + data.messages[i].messageid + "' class=\"msg_node\" >";
						bakInfo += "<div class=\"msg_body\">";
						bakInfo += "<a href='#'  tid='" + data.messages[i].messageid + "' class=\"msg_from\">";
						if(data.messages[i].sender.trim() != "") {
							bakInfo += data.messages[i].sender + ":";
						}
						bakInfo += "</a>";
						bakInfo += data.messages[i].content;
						bakInfo += "</div>";
						bakInfo += "<div class=\"msg_attachment\">";
						if(data.messages[i].attachment.length > 0)
							bakInfo += "附件：";
						for(var j = 0; j < data.messages[i].attachment.length; j++) {
							bakInfo += "<a href='#' id='file_" + data.messages[i].attachment[j].fileId + "'>" + data.messages[i].attachment[j].fileName + "</a>"
						}
						bakInfo += "</div>";
						bakInfo += "<div class=\"msg_funbtn\">";
						bakInfo += "<div class=\"msg_header\">";
						bakInfo += "<a tid='" + data.messages[i].messageid + "' class='msg_read' href='#'>已阅</a>";
						bakInfo += "<a  tid='" + data.messages[i].messageid + "'  class='msg_replay' href='#'>回复</a>";
						bakInfo += "<span class=\"msg_time\">";
						bakInfo += data.messages[i].time.substring(0, data.messages[i].time.length - 3);
						bakInfo += "</span>";
						bakInfo += "</div>";
						//<div tid='" + data.messages[i].messageid + "' class=\"msg_rmvbtn\">
						bakInfo += "</div></div>";
						bakInfo += "</div>";
					}
					var next = data.next_cursor
					callback(bakInfo, next);
				}
			}, function(err) {
				error(err);
			});
		},
		//寻呼回复
		replyUnreadMessage : function(obj, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/ReplyUnreadMessage";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			variables.replyId = obj.replyId;
			variables.content = obj.content;
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback();
				}
			}, function(err) {
				error(err);
			});
		},
		//寻呼设置已阅
		setMessageRead : function(id, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/SetMessageRead";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			variables.messageIds = id;
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				var bakInfo = "";
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback();
				}
			}, function(err) {
				error(err);
			});
		},
		//获取个人日记列表
		getDiaryList : function(cursor, count, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetDiaryList";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			variables.cursor = cursor.toString();
			variables.count = count.toString();
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				var bakInfo = "";
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					for(var i = 0; i < data.diarys.length; i++) {
						bakInfo += "<div index='" + i + "' flag='0' class=\"diary_node\" >";
						bakInfo += "<span class='diary_time'>"
						var dateTime = data.diarys[i].diaryTime.replace("0:00:00", "");
						bakInfo += dateTime.split("-")[1] + "月" + dateTime.split("-")[2].trim() + "日";
						bakInfo += "</span>"
						bakInfo += "<span class='diary_content'>"
						for(var j = 0; j < data.diarys[i].templates.length; j++) {
							for(var k = 0; k < data.diarys[i].templates[j].diaryNodes.length; k++) {
								bakInfo += data.diarys[i].templates[j].diaryNodes[k];
							}
						}
						bakInfo += "</span>";
						bakInfo += "</div>"
					}
					var next = data.next_cursor
					callback(bakInfo, data);
				}
			}, function(err) {
				error(err);
			});
		},
		//日记保存
		saveDiary : function(content, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/SaveDiary";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);

			variables.diaryContent = content;
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback();
				}
			}, function(err) {
				error(err);
			});
		},
		//文件下载
		getFile : function(fileId, part, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetFile";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			variables.fileId = fileId;
			variables.part = part;
			//返回数据类型
			variables.dataType = "json";
			var userInfo = Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback(data);
				}
			}, function(err) {
				error(err);
			});
		},
		//人员搜索
		getSearchData : function(tip, callback, error) {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "select * from user  where username like @tip";
			_stmt.parameters["@tip"] = "%" + tip + "%";
			_sqlstatus = "getsearchdata";
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
			var deptList = new Array();
			deptList[0] = _tempdeptid;
			if(_tempdeptid === 0) {
				callback(deptList);
			} else {
				GetFDept(_tempdeptid, deptList);
				callback(deptList);
			}
		},
		//更新关注人员
		UpdateCareUserInfo : function(uid, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetOUserInfo";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			//指定用户ID
			variables.userId = uid;
			//返回数据类型
			variables.dataType = "json";
			Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					//打开数据库连接
					initDB();
					_stmt.clearParameters();
					var config = App.getConfig();
					_stmt.text = "update UserCare set UserName=@UserName,DeptName=@DeptName,PosiName=@PosiName,TeleNum=@TeleNum,UserTel=@UserTel where TUID=@TUID and UID=@UID";
					_stmt.parameters["@UID"] = uid;
					_stmt.parameters["@UserName"] = data.userName;
					_stmt.parameters["@DeptName"] = data.deptName;
					_stmt.parameters["@PosiName"] = data.posiName;
					_stmt.parameters["@TeleNum"] = data.teleNum;
					_stmt.parameters["@UserTel"] = data.userTel;
					_stmt.parameters["@TUID"] = config.LoginCode;
					_stmt.execute();
					//销毁数据库连接
					disposeDB();
					if(data.photoCode == null || data.photoCode == "") {
						callback(data, 0);
					} else {
						//个人头像
						var file = new air.File(air.File.applicationDirectory.resolvePath("app:/assets/images/photos/" + uid + ".jpg").nativePath);
						var byteData = new air.ByteArray();
						Base64.decode(data.photoCode, byteData);
						var stream = new air.FileStream();
						stream.open(file, air.FileMode.WRITE);
						stream.writeBytes(byteData, 0, byteData.length);
						stream.close();
						callback(data, 1);
					}
				}
			}, function(err) {
				error(err);
			});
		},
		//获取所有总部信息
		getOrg : function(callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetUserList";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			//请求数据格式
			variables.dataStyle = "0";
			//返回数据类型
			variables.dataType = "json";
			Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback(data);
				}
			}, function(err) {
				error(err);
			});
		},
		//设置临时过渡数据
		setTempData : function(data) {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "delete from tempdata";
			_stmt.execute();
			_stmt.clearParameters();
			_stmt.text = "insert into tempdata(data) values(@data)";
			_stmt.parameters["@data"] = data;
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
		},
		//提取临时过渡数据
		getTempData : function() {
			//打开数据库连接
			initDB();
			_stmt.clearParameters();
			_stmt.text = "select * from  tempdata";
			_sqlstatus = "gettempdata";
			_stmt.execute();
			//销毁数据库连接
			disposeDB();
			return _tempdata;
		},
		//历史寻呼
		getCallContent : function(callId, callback, error) {
			//默认用户已经登录成功
			var config = App.getConfig();
			//web service 登录认证地址
			var url = config.WsURL + "/GetCallContent";
			var variables = new air.URLVariables();
			//用户名和密码用$连接
			variables.sign = config.LoginCode + "$" + SHA1.hex_sha1_u(config.Password);
			//请求数据格式
			variables.callId = callId;
			//返回数据类型
			variables.dataType = "json";
			Net.getJSON(url, variables, function(data) {
				if(data.error == "1") {
					error(data.errorMessage);
				} else {
					callback(data);
				}
			}, function(err) {
				error(err);
			});
		},
		//
		createMsgRightNode : function(msg, time) {
			var msgStr = "";
			msgStr += "<div class=\"msg_node_right\">";
			msgStr += "<table cellpadding=\"0\" cellspacing=\"0\" >";
			msgStr += "<tr>";
			msgStr += "<td colspan=\"2\" class=\"msg_node_date_right\" >" + time + "</td>";
			msgStr += "</tr>";
			msgStr += "<tr>";
			msgStr += "<td class=\"msg_node_content_right\"><div>" + msg + "</div></td>";
			msgStr += "<td class=\"msg_node_arrow_content\"><div class=\"msg_node_arrow_right\"></div></td>";
			msgStr += "</tr></table></div>";
			return msgStr;
		},
		//
		createMsgLeftNode : function(msg, time) {
			var msgStr = "";
			msgStr += "<div class=\"msg_node_left\">";
			msgStr += "<table cellpadding=\"0\" cellspacing=\"0\" >";
			msgStr += "<tr>";
			msgStr += "<td colspan=\"2\" class=\"msg_node_date_left\" >" + time + "</td>";
			msgStr += "</tr>";
			msgStr += "<tr>";
			msgStr += "<td class=\"msg_node_arrow_content\"><div class=\"msg_node_arrow_left\"></div></td>";
			msgStr += "<td class=\"msg_node_content_left\"><div>" + msg + "</div></td>";
			msgStr += "</tr></table></div>";
			return msgStr;
		},
		backupToXML : function() {
			var xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
			xmlStr += "<careusers>";
			App.getCareUserList(function(fun, userList) {
				for(var i = 0; i < userList.length; i++) {
					xmlStr += "<item>";
					xmlStr += "<UID>" + userList[i].userID + "</UID>";
					xmlStr += "<UserName>" + userList[i].userName + "</UserName>";
					xmlStr += "<DeptName>" + userList[i].deptName + "</DeptName>";
					xmlStr += "<PosiName>" + userList[i].posiName + "</PosiName>";
					xmlStr += "<TeleNum>" + userList[i].teleNum + "</TeleNum>";
					xmlStr += "<UserTel>" + userList[i].userTel + "</UserTel>";
					xmlStr += "<TUID>" + userList[i].tUID + "</TUID>";
					xmlStr += "</item>";
				}
				xmlStr += "</careusers>";
				xmlStr += "<config>";
				var appConfig = App.getConfig();
				for(name in appConfig) {
					if( typeof appConfig[name] !== 'function') {
						if(appConfig[name] == "") {
							if(appConfig[name] === 0) {
								appConfig[name] = "0";
								xmlStr += "<item key=\"" + name + "\">";
								xmlStr += appConfig[name].toString();
								xmlStr += "</item>";
							}
						} else {
							if(appConfig[name] === 0) {
								appConfig[name] = "0";

							}
							xmlStr += "<item key=\"" + name + "\">";
							xmlStr += appConfig[name].toString();
							xmlStr += "</item>";
						}
					}
				}
				xmlStr += "</config>";
				var file = new air.File(air.File.applicationDirectory.resolvePath("app:/config/bak.xml").nativePath);
				var stream = new air.FileStream();
				stream.open(file, air.FileMode.WRITE);
				stream.writeUTFBytes(xmlStr);
				stream.close();
			});
		},
		recoverFromXML : function() {
			var file = new air.File(air.File.applicationDirectory.resolvePath("app:/config/bak.xml").nativePath);
			if(file.exists) {
				var stream = new air.FileStream();
				stream.open(file, air.FileMode.READ);
				var bakInfo = stream.readUTFBytes(stream.bytesAvailable);
				stream.close();
				var Domp = new DOMParser();
				var xmlDom = Domp.parseFromString(bakInfo, "text/xml");
				//打开数据库连接
				initDB();

				//清空所有关注人员
				_stmt.clearParameters();
				_stmt.text = "delete from UserCare";
				_stmt.execute();
				//恢复关注人员
				_conn.begin();
				$(xmlDom).find("careusers item").each(function() {
					_stmt.clearParameters();
					_stmt.text = "insert into Usercare(UID,UserName,DeptName,PosiName,TeleNum,UserTel,TUID) values(@UID,@UserName,@DeptName,@PosiName,@TeleNum,@UserTel,@TUID)";
					_stmt.parameters["@UID"] = $(this).find("UID").eq(0).text();
					_stmt.parameters["@UserName"] = $(this).find("UserName").eq(0).text();
					_stmt.parameters["@DeptName"] = $(this).find("DeptName").eq(0).text();
					_stmt.parameters["@PosiName"] = $(this).find("PosiName").eq(0).text();
					_stmt.parameters["@TeleNum"] = $(this).find("TeleNum").eq(0).text();
					_stmt.parameters["@UserTel"] = $(this).find("UserTel").eq(0).text();
					_stmt.parameters["@TUID"] = $(this).find("TUID").eq(0).text();
					_stmt.execute();
				});
				//恢复配置信息
				$(xmlDom).find("config item").each(function() {
					_stmt.clearParameters();
					_stmt.text = "update config set Value=@Value where Key=@Key";
					_stmt.parameters["@Value"] = $(this).text();
					_stmt.parameters["@Key"] = $(this).attr("key");
					_stmt.execute();
				});
				_conn.commit();

				//销毁数据库连接
				disposeDB();
				//恢复完成，删除备份文件
				file.deleteFile();
			}
		}
	}
}();
